using System.Collections.Generic;
using SO;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace Backpack
{
    public class BackpackUI : MonoBehaviour, ICanRegisterEvent
    {
        public List<ItemCell> itemCells;

        private IItemUI currentSelectedItem;

        [SerializeField] private Transform itemPabelTf;
        [SerializeField] private ItemCell itemCellPrefab;

        [Space]

        [SerializeField] private TextMeshProUGUI descriptionText;
        [SerializeField] private Button combineButton;
        [SerializeField] private Button useButton;


        private void OnEnable()
        {
            this.RegisterEvent<BackpackSystem.UpdateItemCellEvent>(UpdateCell).UnRegisterEventWhenBeDistroyed(gameObject);
        }
        private void OnDisable()
        {
            ResetStatus();
            //重置状态
        }

        private void ResetStatus()
        {
            currentSelectedItem = null;
            CombineSystem.Instance.IsCombinng = false;
            CombineSystem.Instance.ItemToCombine.Clear();
            descriptionText.text = string.Empty;
        }
        private void Start()
        {
            int count = BackpackSystem.Instance.CellCount;

            for (int i = 0; i < count; i++)
            {
                var itemCell = Instantiate(itemCellPrefab, itemPabelTf);
                itemCells.Add(itemCell);
            }
            BackpackSystem.Instance.RefreshBackpack();

            combineButton.onClick.AddListener(OnCombineButtonClicked);
            useButton.onClick.AddListener(OnUseButtonClicked);
        }
        private void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                PointerEventData pointer = new PointerEventData(EventSystem.current);
                pointer.position = Input.mousePosition;
                List<RaycastResult> raycastResults = new List<RaycastResult>();
                EventSystem.current.RaycastAll(pointer, raycastResults);

                if (raycastResults.Count > 0)
                {
                    GameObject clickedObject = raycastResults[0].gameObject;
                    if (CombineSystem.Instance.IsCombinng == false)
                    {
                        //获取第一个被点击的UI物体（通常是最上层的）
                        if (clickedObject.TryGetComponent<IItemUI>(out var itemUI))
                        {
                            OnSelectItem(itemUI);
                        }
                    }
                    else
                    {
                        Debug.Log("asdasdasda");
                        if (clickedObject.TryGetComponent<IItemUI>(out var itemUI))
                        {
                            AddItemToCombine(itemUI.ItemData);
                            Debug.Log("Added item to combine: " + itemUI.ItemData.itemName);
                        }
                    }
                }
            }
        }
        private void UpdateCell(BackpackSystem.UpdateItemCellEvent updateItemCellEvent)
        {
            itemCells[updateItemCellEvent.itemCellData.index].UpdateCell(updateItemCellEvent.itemCellData);
        }

        private void OnCombineButtonClicked()
        {
            // if (BackpackModel.Instance.isCombining == false)
            // {
            //     if (currentSelectedItemCell != null)
            //     {
            //         AddItemToCombine(currentSelectedItemCell);
            //         currentSelectedItemCell = null;
            //     }
            // }
            // else if (BackpackModel.Instance.isCombining)
            // {
            //     descriptionText.text = "";
            //     itemCellToCombine.Clear();
            // }
            if (CombineSystem.Instance.IsCombinng == false)
            {
                descriptionText.text = "请选择要合成的物品";

                CombineSystem.Instance.ItemToCombine.Clear();

                CombineSystem.Instance.IsCombinng = true;

                combineButton.GetComponentInChildren<TextMeshProUGUI>().text = "确认";
            }
            else
            {
                descriptionText.text = "";

                int targetId = CombineSystem.Instance.Combine();
                Debug.Log("TargetId: " + targetId);
                if (targetId != -1)
                {
                    foreach (var itemData in CombineSystem.Instance.ItemToCombine)
                    {
                        BackpackSystem.Instance.RemoveItem(itemData.id);
                    }
                    BackpackSystem.Instance.AddItem(ItemConfigModel.Instance.GetData(targetId));
                }
                CombineSystem.Instance.IsCombinng = false;

                CombineSystem.Instance.ItemToCombine.Clear();

                combineButton.GetComponentInChildren<TextMeshProUGUI>().text = "组合";
            }
        }
        private void OnUseButtonClicked()
        {
            if (currentSelectedItem != null)
            {
                currentSelectedItem.BeUsed();
                BackpackSystem.Instance.RemoveItem(currentSelectedItem.ItemData.id);
            }
        }
        private void AddItemToCombine(ItemDataSO itemDataSO)
        {
            CombineSystem.Instance.AddItemToCombine(itemDataSO);
            Debug.Log("Add item to combine");
            /*if (itemCellToCombine.Count == 2)
            {
                //TODO : combine item]
                int id0 = itemCellToCombine[0].ItemDataSO.id;
                int id1 = itemCellToCombine[1].ItemDataSO.id;

                int targetId = CombineInfomationModel.Instance.Query(id0, id1);
                if (targetId != -1)
                {
                    BackpackSystem.Instance.RemoveItem(id0);
                    BackpackSystem.Instance.RemoveItem(id1);

                    BackpackSystem.Instance.AddItem(ItemConfigModel.Instance.GetData(targetId));
                }
                else
                {
                    //TODO : 取消combining状态  更新文本
                    itemCellToCombine.Clear(); //TODO : 更新网格为未选中状态
                    BackpackModel.Instance.isCombining = false;
                    descriptionText.text = "这两个物品无法合成";
                }
            }*/
        }
        public void OnSelectItem(IItemUI itemUI)
        {
            currentSelectedItem = itemUI;
            descriptionText.text = itemUI.ItemData.description;
        }
    }
}